package com.cjl.net.bio;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class BIOServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress("127.0.0.1",40000));
        BlockingQueue blockingQueue = new ArrayBlockingQueue(20);
        ExecutorService executorService = new ThreadPoolExecutor(10, 100, 5000, TimeUnit.MILLISECONDS, blockingQueue);
        System.out.println("Server.main start");
        try {
            while (true){
                executorService.execute(new ServerTask(serverSocket.accept()));
            }
        }finally {
            serverSocket.close();
        }
    }

    private static class ServerTask implements Runnable{
        private Socket socket;

        public ServerTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //1.7 新增try with resource 实现 AutoCloseable的

            try(ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());){
                String name = inputStream.readUTF();
                System.out.println("ServerTask.run hi,"+name);
                outputStream.writeUTF("需要几号技师");
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
